package com.zhq.cxf.intercept;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.List;

/**
 * <pre>
 * @class com.zhq.cxf.intercept.AuthHeaderIntercept
 * @description soapHeader校验拦截器
 * @author zhq
 * @date 2022/6/2 15:04
 * </pre>
 */
@Slf4j
@Component
public class AuthHeaderIntercept extends AbstractPhaseInterceptor<SoapMessage> {


    public AuthHeaderIntercept() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {

        log.info("soapHeader校验开始。。。");
        List<Header> headers = soapMessage.getHeaders();

        if (null == headers || headers.size() <= 0){
            throw new Fault(new IllegalArgumentException("error soapHeader..."));
        }

        for (Header header : headers) {

            Element root = (Element)header.getObject();
            String namespaceURI = root.getNamespaceURI();
            String localName = root.getLocalName();
            log.info(String.format("namespaceURI: %s", namespaceURI));
            log.info(String.format("localName: %s", localName));

            NodeList childNodes = root.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                String name = item.getNodeName();
                String value = item.getTextContent();
                log.info(String.format("name: %s", name));
                log.info(String.format("value: %s", value));

            }

        }
        log.info("soapHeader校验结束！");
    }
}
